//
// Created by 文道江 on 15/12/1.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "UpgradeSplashPlugin.h"
#import "UpgradeManger.h"

#define SPLASH_SHOW_INDEX_KEY @"splash_show_index"
#define SPLASH_CONFIG_FILE_NAME @"splash.json"


@implementation UpgradeSplashPlugin {
    UpgradeManger *_upgradeManger;
    SplashScreenView *_screenView;
    NSDictionary *_splashItem;
    UIView *_upgradeView;
    NSString *_upgradeDownloadUrl;
}

- (void)pluginInitialize{
     NSDictionary *appInfo = [HybridBridge defaultHybridBridge].appInfo;
    if (appInfo[@"UpgradeUrl"] != nil){
        NSString *UpgradeUrl = appInfo[@"UpgradeUrl"];
        if (IS_DEBUG && appInfo[@"UpgradeUrlDebug"])UpgradeUrl = appInfo[@"UpgradeUrlDebug"];
        _upgradeManger = [[UpgradeManger alloc] initWithAppId:appInfo[@"AppId"] AppKey:appInfo[@"AppKey"] upgradeUrl:UpgradeUrl];
        [_upgradeManger checkUpgrade:^BOOL(BOOL newVersion, id info) {
            if(newVersion){
                //[self hideSplash];
                [self showUpgrade];
            }
            if ([info isKindOfClass:[NSDictionary class]] && info[@"upgradeNative"]){
                NSDictionary *nativeInfo = info[@"upgradeNative"];
                NSString *title = @"更新提示";
                NSString *updateButtonTitle = @"升级";
                NSString *cancelButtonTitle = @"取消";

                _upgradeDownloadUrl = nativeInfo[@"file"];

                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nativeInfo[@"title"] == nil ? title : nativeInfo[@"title"]
                                                                    message:nativeInfo[@"note"] == nil ? title : nativeInfo[@"note"]
                                                                   delegate:self
                                                          cancelButtonTitle:nativeInfo[@"cancelButton"] == nil ? cancelButtonTitle : nativeInfo[@"cancelButton"]
                                                          otherButtonTitles:nativeInfo[@"updateButton"] == nil ? updateButtonTitle : nativeInfo[@"updateButton"], nil];

                [alertView show];
            }
            return newVersion;
        } done:^(NSDictionary *versionInfo, NSError *error) {
            if (versionInfo[@"upgrade"] && (/*_screenView != nil ||*/ _upgradeView != nil)){
                NSURL *url = self.webView.URL;
                if (url == nil || [url.absoluteString isEqualToString:@""]){
                    url = [NSURL URLWithString:[@"file://" stringByAppendingFormat:@"%@", [FZEasyFile fullFileName:@"web/index.html"]]];
                }
                [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
                [self.webView reload];
            }
            [NSThread sleepForTimeInterval:0.2];
            if (_upgradeView != nil){
                [self hideUpgrade: YES];
            }
        }];
    }
    [self showSplash];
}

- (void)showSplash{
    NSDictionary *item = [self loadSplashItem];
    if (item == nil)
        return;
    _splashItem = item;

    _screenView = [SplashScreenView viewWithFrame:self.webView.frame Image:nil showTime: 0];
    _screenView.delegate = self;
    _screenView.showControl = [_splashItem[@"showControl"] boolValue];
    _screenView.showCountdown = [_splashItem[@"showCountdown"] boolValue];

    NSString *imagePath = [_upgradeManger localPathWithURL:_splashItem[@"image"]];
    [NSThread sleepForTimeInterval:0.2];

    UIImage *image = [UIImage imageWithContentsOfFile:[FZEasyFile fullFileName:imagePath]];
    [_screenView showWithImage:image Time:[_splashItem[@"showTime"] integerValue]];
    [self.webView insertSubview:_screenView atIndex:2];
}

- (void)hideSplash{
    if (_screenView != nil){
        [_screenView hide:YES];
        _screenView = nil;
    }
}

- (void)showUpgrade{
    _upgradeView = [[UIView alloc] initWithFrame:self.webView.frame];
    _upgradeView.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0, _upgradeView.frame.size.width, 30)];
    label.center = CGPointMake(_upgradeView.frame.size.width / 2, _upgradeView.frame.size.height / 2);
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor grayColor];
    label.text = @"数据更新中";
    [_upgradeView addSubview:label];

    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, label.center.y - 30, 200, 30)];
    progressView.center = CGPointMake(_upgradeView.frame.size.width / 2, label.center.y - 30);
    progressView.progressViewStyle = UIProgressViewStyleDefault;
    progressView.progress = 0.0;

    [_upgradeView addSubview:progressView];

    [self.webView insertSubview:_upgradeView atIndex:1];

    [[HybridEventBus defaultEventBus] subscribe:@"downloadUpgradeProgress" UsingBlock:^(NSNotification *notification) {
        NSProgress *progress = notification.userInfo[@"progress"];
        if (progress){
            dispatch_async(dispatch_get_main_queue(), ^{
                progressView.progress = (float) progress.fractionCompleted;
            });
            NSLog(@"Progress is %f", progress.fractionCompleted);
        }
    }];

}

- (void)hideUpgrade:(BOOL) animated{
    if (_upgradeView != nil){
        if (animated){
            if ([_upgradeView.layer animationForKey:@"opacity"] == nil){
                CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
                opacityAnimation.fromValue = @1.0F;
                opacityAnimation.toValue = @0.0F;
                opacityAnimation.duration = 1.5f;
                opacityAnimation.repeatCount = 1;
                [_upgradeView.layer addAnimation:opacityAnimation forKey:@"opacity"];
                [NSTimer scheduledTimerWithTimeInterval:1.4f target:_upgradeView selector:@selector(removeFromSuperview) userInfo:nil repeats:NO];
            }else{
                [_upgradeView.layer removeAllAnimations];
            }
        }else{
            [_upgradeView removeFromSuperview];
        }

    }
}

- (NSDictionary *)loadSplashItem{
    NSString *path = [FZEasyFile fullFileName:SPLASH_CONFIG_FILE_NAME];
    if ([FZEasyFile isFileExists:SPLASH_CONFIG_FILE_NAME]) {
        NSArray *splashs = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingAllowFragments error:nil];
        if (splashs && splashs.count > 0) {
            NSNumber *number = [KVStorage getValue:SPLASH_SHOW_INDEX_KEY];
            [KVStorage setKey:SPLASH_SHOW_INDEX_KEY Value:@(number.integerValue + 1)];
            NSDictionary *item = splashs[number.integerValue % splashs.count];
            NSString *imgPath = [_upgradeManger localPathWithURL:item[@"image"]];
            if ([FZEasyFile isFileExists:imgPath]) {
                return item;
            }
        }
    }
    NSDictionary *appInfo = [HybridBridge defaultHybridBridge].appInfo;
    if(appInfo && appInfo[@"defaultSplash"]){
        NSDictionary *defaultSplash = appInfo[@"defaultSplash"];
        if ([defaultSplash[@"image"] hasPrefix:@"file:///ios_asset/"]){
            NSMutableDictionary *newSplash = [defaultSplash mutableCopy];
            newSplash[@"image"] = [newSplash[@"image"] stringByReplacingOccurrencesOfString:@"file:///ios_asset/" withString:[NSBundle mainBundle].bundleURL.absoluteString];
            return newSplash;
        }
        return defaultSplash;
    }
    return nil;
}


#pragma mark SplashScreenViewDelegate

- (void)imageClick:(UIImageView *)imageView {
    if (_splashItem) {
        NSString *url = _splashItem[@"url"];
        if (url != nil && url.length > 5){
            [self.bridge executeAction:@"Core/openWindow" Params:@{@"url" : _splashItem[@"url"]} Handler:nil];
        }
    }
}

- (void)imageDidLoadError:(NSError *)error {

    NSLog(@"imageDidLoadError : %@", error);
    if (_screenView != nil){
        [_screenView removeFromSuperview];
    }
}

- (void)viewHidden {

}


#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 1 && _upgradeDownloadUrl != nil){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_upgradeDownloadUrl]];
    }
}

@end

